package cn.zust.itcost.service.impl;

import cn.zust.itcost.entity.graph.node.*;
import cn.zust.itcost.repository.ResumeRepository;
import cn.zust.itcost.service.ResumeInferenceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ResumeInferenceServiceImpl implements ResumeInferenceService {

    @Autowired
    private ResumeRepository resumeRepository;

    // 行业技能需求数据
    private static final Map<String, List<String>> INDUSTRY_SKILL_DEMANDS = Map.of(
        "互联网", Arrays.asList("Java", "Python", "Spring", "微服务", "分布式", "大数据"),
        "金融", Arrays.asList("风控", "数据分析", "Python", "SQL", "机器学习"),
        "教育", Arrays.asList("教学", "课程设计", "教育技术", "Python", "数据分析")
    );

    // 职位技能要求
    private static final Map<String, List<String>> POSITION_SKILL_REQUIREMENTS = Map.of(
        "Java开发工程师", Arrays.asList("Java", "Spring", "MySQL", "Redis", "微服务"),
        "数据分析师", Arrays.asList("Python", "SQL", "数据分析", "机器学习", "统计学"),
        "产品经理", Arrays.asList("产品设计", "需求分析", "Axure", "项目管理", "用户研究")
    );

    @Override
    public Map<String, Object> analyzeCareerPath(Long resumeId) {
        ResumeNode resume = resumeRepository.findById(resumeId)
            .orElseThrow(() -> new RuntimeException("简历不存在"));
        
        List<String> careerPaths = new ArrayList<>();
        Map<String, Object> result = new HashMap<>();
        
        // 分析当前技能组合
        Set<String> currentSkills = resume.getSkills().stream()
            .map(SkillNode::getName)
            .collect(Collectors.toSet());
        
        // 根据技能组合推荐职业路径
        if (currentSkills.contains("Java") || currentSkills.contains("Python")) {
            careerPaths.add("技术路线：初级开发工程师 -> 高级开发工程师 -> 技术专家 -> 架构师");
            careerPaths.add("管理路线：开发工程师 -> 技术主管 -> 技术经理 -> CTO");
        }
        
        if (currentSkills.contains("数据分析") || currentSkills.contains("机器学习")) {
            careerPaths.add("分析路线：数据分析师 -> 高级数据分析师 -> 数据科学家");
            careerPaths.add("管理路线：数据分析师 -> 数据分析主管 -> 数据总监");
        }
        
        result.put("careerPaths", careerPaths);
        result.put("currentSkills", currentSkills);
        result.put("suggestions", generateCareerSuggestions(resume));
        
        return result;
    }

    @Override
    public Map<String, Object> analyzeSkillRelations(Long resumeId) {
        ResumeNode resume = resumeRepository.findById(resumeId)
            .orElseThrow(() -> new RuntimeException("简历不存在"));
        
        Map<String, Object> result = new HashMap<>();
        
        // 分析技能关联
        Set<String> currentSkills = resume.getSkills().stream()
            .map(SkillNode::getName)
            .collect(Collectors.toSet());
        
        // 找出相关技能组合
        List<String> skillCombinations = new ArrayList<>();
        if (currentSkills.contains("Java") && !currentSkills.contains("Spring")) {
            skillCombinations.add("建议学习Spring框架，与Java技能形成完整的技术栈");
        }
        if (currentSkills.contains("Python") && !currentSkills.contains("数据分析")) {
            skillCombinations.add("建议学习数据分析，与Python技能形成完整的数据分析能力");
        }
        
        // 推荐互补技能
        List<String> complementarySkills = new ArrayList<>();
        for (String skill : currentSkills) {
            if (skill.equals("Java")) {
                complementarySkills.add("Spring");
                complementarySkills.add("微服务");
            }
            if (skill.equals("Python")) {
                complementarySkills.add("数据分析");
                complementarySkills.add("机器学习");
            }
        }
        
        result.put("currentSkills", currentSkills);
        result.put("skillCombinations", skillCombinations);
        result.put("complementarySkills", complementarySkills);
        
        return result;
    }

    @Override
    public Map<String, Object> analyzeIndustryInsights(Long resumeId) {
        ResumeNode resume = resumeRepository.findById(resumeId)
            .orElseThrow(() -> new RuntimeException("简历不存在"));
        
        Map<String, Object> result = new HashMap<>();
        
        // 分析行业趋势匹配度
        String industry = determineIndustry(resume);
        List<String> industrySkills = INDUSTRY_SKILL_DEMANDS.getOrDefault(industry, new ArrayList<>());
        
        Set<String> currentSkills = resume.getSkills().stream()
            .map(SkillNode::getName)
            .collect(Collectors.toSet());
        
        // 计算技能匹配度
        long matchedSkills = industrySkills.stream()
            .filter(currentSkills::contains)
            .count();
        double matchRate = (double) matchedSkills / industrySkills.size();
        
        // 行业薪资水平
        Map<String, String> salaryLevels = Map.of(
            "互联网", "15-30k",
            "金融", "20-35k",
            "教育", "10-25k"
        );
        
        result.put("industry", industry);
        result.put("skillMatchRate", matchRate);
        result.put("salaryLevel", salaryLevels.getOrDefault(industry, "未知"));
        result.put("hotSkills", industrySkills);
        result.put("trends", getIndustryTrends(industry));
        
        return result;
    }

    @Override
    public Map<String, Object> getSkillUpgradeSuggestions(Long resumeId, String targetPosition) {
        ResumeNode resume = resumeRepository.findById(resumeId)
            .orElseThrow(() -> new RuntimeException("简历不存在"));
        
        Map<String, Object> result = new HashMap<>();
        
        // 获取目标职位所需技能
        List<String> requiredSkills = POSITION_SKILL_REQUIREMENTS.getOrDefault(targetPosition, new ArrayList<>());
        
        // 当前技能
        Set<String> currentSkills = resume.getSkills().stream()
            .map(SkillNode::getName)
            .collect(Collectors.toSet());
        
        // 找出技能差距
        List<String> missingSkills = requiredSkills.stream()
            .filter(skill -> !currentSkills.contains(skill))
            .collect(Collectors.toList());
        
        // 生成学习建议
        List<String> suggestions = new ArrayList<>();
        for (String skill : missingSkills) {
            suggestions.add(String.format("建议学习%s，这是%s职位的核心技能", skill, targetPosition));
        }
        
        result.put("targetPosition", targetPosition);
        result.put("currentSkills", currentSkills);
        result.put("requiredSkills", requiredSkills);
        result.put("missingSkills", missingSkills);
        result.put("suggestions", suggestions);
        
        return result;
    }

    private String determineIndustry(ResumeNode resume) {
        // 根据工作经历判断行业
        for (ExperienceNode experience : resume.getExperiences()) {
            String company = experience.getCompany().toLowerCase();
            if (company.contains("科技") || company.contains("网络") || company.contains("互联网")) {
                return "互联网";
            }
            if (company.contains("银行") || company.contains("证券") || company.contains("金融")) {
                return "金融";
            }
            if (company.contains("教育") || company.contains("学校") || company.contains("培训")) {
                return "教育";
            }
        }
        return "其他";
    }

    private List<String> generateCareerSuggestions(ResumeNode resume) {
        List<String> suggestions = new ArrayList<>();
        
        // 根据教育背景给出建议
        for (EducationNode education : resume.getEducations()) {
            if (education.getMajor().contains("计算机") || education.getMajor().contains("软件")) {
                suggestions.add("建议关注技术路线发展，可以考虑向架构师方向发展");
            }
            if (education.getMajor().contains("数学") || education.getMajor().contains("统计")) {
                suggestions.add("建议关注数据分析方向，可以考虑向数据科学家方向发展");
            }
        }
        
        // 根据工作经历给出建议
        int experienceYears = calculateExperienceYears(resume);
        if (experienceYears < 3) {
            suggestions.add("建议在现有领域深耕，积累更多项目经验");
        } else if (experienceYears < 5) {
            suggestions.add("可以考虑向高级职位发展，或开始接触管理岗位");
        } else {
            suggestions.add("建议考虑向专家或管理方向发展，可以开始培养领导力");
        }
        
        return suggestions;
    }

    private int calculateExperienceYears(ResumeNode resume) {
        int totalYears = 0;
        for (ExperienceNode experience : resume.getExperiences()) {
            // 简单计算工作年限
            totalYears += 1;
        }
        return totalYears;
    }

    private List<String> getIndustryTrends(String industry) {
        switch (industry) {
            case "互联网":
                return Arrays.asList(
                    "微服务架构持续流行",
                    "云原生技术快速发展",
                    "AI和大数据应用广泛"
                );
            case "金融":
                return Arrays.asList(
                    "金融科技快速发展",
                    "区块链技术应用增加",
                    "智能投顾兴起"
                );
            case "教育":
                return Arrays.asList(
                    "在线教育持续增长",
                    "教育科技应用广泛",
                    "个性化学习需求增加"
                );
            default:
                return Collections.singletonList("行业趋势信息暂缺");
        }
    }
} 